//
//  AppController.m
//  Networking
//
//  Created by Christoph Eßer on 11/25/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"
#import <Foundation/Foundation.h>
#import "NetworkMessage.h"

@implementation AppController

- (id)initWithWindow:(NSWindow *)window
{
    self = [super initWithWindow:window];
    if (self) {
        //init thread controllers and set message delegate to receive incoming messages
        stc = [[ServerThreadController alloc] init];
        ctc = [[ClientThreadController alloc] init];
        
        [stc setMessageDelegate:self];
        [ctc setMessageDelegate:self];
        
        serverPort = 31775;
    }
    
    return self;
}

- (void)dealloc
{
    [super dealloc];
    //stop networking threads, then release objects
    [ctc stopNetworkingThread];
    [stc stopServerThread];
    
    [stc release];
    [ctc release];
}

- (void)windowDidLoad
{
    [super windowDidLoad];
    
    // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}

- (IBAction)startServerClick:(id)sender {
    [stc startServerThreadOnPort:serverPort];
}

- (IBAction)connectClientClick:(id)sender {
    [ctc startNetworkingThreadConnectToAddress:@"127.0.0.1" onPort:serverPort];
}

- (IBAction)disconnectClientClick:(id)sender {
    [ctc stopNetworkingThread];
}


- (IBAction)sendMsgToServerClick:(id)sender { 
    //create test message, then send it to server using the client thread controller
    NetworkMessage *msg = [[NetworkMessage alloc] initWithString:@"TestMessage!"];
    [ctc sendMessageToServer:[msg retain]];
    [msg release];
}

- (IBAction)stopServerClick:(id)sender {
    [stc stopServerThread];
}

- (IBAction)sendMsgToClientClick:(id)sender {
    //create test message, then send it to all clients using the server thread controller
    NetworkMessage *msg = [[NetworkMessage alloc] initWithString:@"TestMessage!"];
    [stc sendMessageToAllClients:msg];
    [msg release];
}

//incoming Message for client, 
-(void) incomingMessage:(NetworkMessage *)msg{
    switch(msg.type) {
        case kStringMessage:
            NSLog(@"CLIENT: Incoming Text Message %@", [msg stringMessage]);
            break;
        default:
            break;
    }
}

//incoming Message for server, handles string messages only atm
-(void) incomingMessage:(NetworkMessage*) msg fromClient:(NSString*) client {
    switch(msg.type) {
        case kStringMessage:
            NSLog(@"SERVER: Incoming Text Message %@ from client %@", [msg stringMessage], client);
            break;
        case kLocationMessage:
            NSLog(@"Location Received");
        default:
            break;
    }
}

//This will be called if a client aborted for a longtime. The networking part will asked the server to remove the connection.
-(void)clientDisconnected:(NSString*) client {
    
}

@end
